package com.hua.yuan.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hua.yuan.MainActivity;
import com.hua.yuan.R;
import com.hua.yuan.base.Constents;
import com.hua.yuan.common.BaseActivity;
import com.hua.yuan.ui.adapter.VideoDesAdapter;
import com.hua.yuan.ui.data.PlayDataRequest;
import com.hua.yuan.ui.data.VideoDataRequest;
import com.hua.yuan.ui.module.CommentInfoBean;
import com.hua.yuan.ui.module.DisBean;
import com.hua.yuan.ui.module.MovieDisBean;
import com.hua.yuan.ui.module.MovieInfo69Bean;
import com.hua.yuan.util.TimeUtils;
import com.hua.yuan.util.ToastUtil;
import com.hua.yuan.view.player.DensityUtil;
import com.hua.yuan.view.player.MediaController;
import com.hua.yuan.view.player.SuperVideoPlayer;
import com.hua.yuan.view.player.TXPlayerAuthParam;
import com.hua.yuan.view.player.VodRspData;
import com.tencent.rtmp.TXPlayerAuthBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cm.hua.yuan.common.utils.PreferenceUtils;
import okhttp3.Call;

/**
 * Created by huangyang on 2018/6/7.
 * 新的详情页
 */

public class VideoDisActivity extends BaseActivity implements View.OnClickListener {


    public static final int TIME_LINE = 20;

    private ImageView backImage;

    private ImageView mPlayBtnView;

    private RelativeLayout disFirstLl;//第一次显示
    private TextView disName;//名字
    private TextView disDisTv;//类型等
    private TextView disJiFei;//显示积分
    private LinearLayout disJianJie;//简介
    private ListView listView;//布局

    private LinearLayout disSecond;//第二显示
    private TextView disName1;//名字
    private ImageView disClose;//关闭第二
    private TextView disShowJianJie;//显示简介

    private TextView bottomLine;//底部的线
    private LinearLayout videoDisBottomLl;//显示地步

    private TextView videoDisSendTv;//发送按钮

    private RelativeLayout buyRlView;
    private TextView videoNameShow;
    private TextView videoBuyMoney;
    private TextView videoKaiTongVip;
    private TextView videoCancelTv;

    private LinearLayout buttonBuyLl;
    private LinearLayout buttonCollectLl;
    private LinearLayout buttonDownLl;

    private EditText sendEt;

    private ImageView collImage;

    private ImageView showFirstImg;

    private VideoDisActivity activity;


    private VideoDesAdapter adapter;

    private MyBroadcastReceiver receiver;
    private DecimalFormat df = new DecimalFormat("######0.0");

    private boolean sendFlag = true;
    private boolean colFlag = true;


    private String videoId = "";

    private MovieDisBean movieDisBean;

    private SuperVideoPlayer mSuperVideoPlayer;

    private String playUrl = "";

    private boolean isBuy = false;
    private boolean isStop = true;//true表示没有停止 false表示停止了

    private String coinNum = "";

    private boolean kMflag = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_new_dis);

        activity = this;

        videoId = getIntent().getStringExtra("id");


        receiver = new MyBroadcastReceiver();
        myRegister();

        PreferenceUtils.setBoolean("is_movie_free", false);


        initView();


        checkPermission();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        initData();


        createData();


        //setWindowBrightness(MainActivity.sysLight);

    }

    private void setWindowBrightness(float brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness;
        window.setAttributes(lp);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isBuy) {
            if (mSuperVideoPlayer != null) {

                if (mSuperVideoPlayer.timeOverTv != null) {
                    mSuperVideoPlayer.timeOverTv.setVisibility(View.GONE);
                }

                if (mSuperVideoPlayer.layout_30_tip != null) {
                    mSuperVideoPlayer.layout_30_tip.setVisibility(View.GONE);
                }

                if (mSuperVideoPlayer.back_pl_1 != null) {
                    mSuperVideoPlayer.back_pl_1.setVisibility(View.GONE);
                }

                if (mSuperVideoPlayer.title_1 != null) {
                    mSuperVideoPlayer.title_1.setVisibility(View.GONE);
                }

                if (isStop) {
                    mSuperVideoPlayer.onResume();
                }

            }
        } else {

            if (isStop) {
                mSuperVideoPlayer.onResume();
            }
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mSuperVideoPlayer != null) {

            int flag = mSuperVideoPlayer.getPlayState();
            if (flag == 1) {
                isStop = true;
            } else {
                isStop = false;
            }

            mSuperVideoPlayer.onPause();
        }
    }

    @Override
    public void finish() {
        super.finish();

        if (handler != null) {
            handler.removeMessages(1);
            handler.removeMessages(2);
            handler.removeCallbacksAndMessages(null);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myUnRegister();
        if (mSuperVideoPlayer != null) {
            mSuperVideoPlayer.onDestroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), 100);
            }
        }
    }

    private void initView() {

        backImage = findViewById(R.id.backImage);
        showFirstImg = findViewById(R.id.showFirstImg);

        disFirstLl = findViewById(R.id.disFirstLl);
        disName = findViewById(R.id.disName);
        disDisTv = findViewById(R.id.disDisTv);
        disJiFei = findViewById(R.id.disJiFei);
        disJianJie = findViewById(R.id.disJianJie);
        listView = findViewById(R.id.listView);

        disSecond = findViewById(R.id.disSecond);
        disName1 = findViewById(R.id.disName1);
        disClose = findViewById(R.id.disClose);
        disShowJianJie = findViewById(R.id.disShowJianJie);

        bottomLine = findViewById(R.id.bottomLine);
        videoDisBottomLl = findViewById(R.id.videoDisBottomLl);


        videoDisSendTv = findViewById(R.id.videoDisSendTv);

        buyRlView = findViewById(R.id.buyRlView);
        videoNameShow = findViewById(R.id.videoNameShow);
        videoBuyMoney = findViewById(R.id.videoBuyMoney);
        videoKaiTongVip = findViewById(R.id.videoKaiTongVip);
        videoCancelTv = findViewById(R.id.videoCancelTv);
        buttonCollectLl = findViewById(R.id.buttonCollectLl);

        buttonBuyLl = findViewById(R.id.buttonBuyLl);

        buttonDownLl = findViewById(R.id.buttonDownLl);

        sendEt = findViewById(R.id.sendEt);

        collImage = findViewById(R.id.collImage);

        mPlayBtnView = findViewById(R.id.play_btn);
        mSuperVideoPlayer = findViewById(R.id.video_player_item_1);

        mSuperVideoPlayer.videoCancelLook.setOnClickListener(this);
        mSuperVideoPlayer.videoConLook.setOnClickListener(this);


        adapter = new VideoDesAdapter(this);


    }

    private void initData() {

        backImage.setOnClickListener(this);
        disJianJie.setOnClickListener(this);
        disClose.setOnClickListener(this);

        videoBuyMoney.setOnClickListener(this);
        videoKaiTongVip.setOnClickListener(this);
        videoCancelTv.setOnClickListener(this);

        buttonBuyLl.setOnClickListener(this);
        buttonCollectLl.setOnClickListener(this);

        videoDisSendTv.setOnClickListener(this);

        buttonDownLl.setOnClickListener(this);

        mPlayBtnView.setOnClickListener(this);


        mSuperVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);


        listView.setAdapter(adapter);

        mSuperVideoPlayer.timeOverTv.setVisibility(View.GONE);


        mSuperVideoPlayer.timeOverTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });


        mSuperVideoPlayer.layout_30_tip.setOnClickListener(this);

        mSuperVideoPlayer.play_lock_rl.setVisibility(View.VISIBLE);
        mSuperVideoPlayer.lock_image.setTag(1);//没有锁屏

        mSuperVideoPlayer.play_lock_rl.setOnClickListener(this);

    }


    private void createData() {

        getVideoDis(videoId);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backImage:
                //返回
                finish();

                break;


            case R.id.disJianJie:
                //点击简介
                showJJie();
                break;

            case R.id.disClose:
                //关闭简介
                closeJJie();
                break;
            case R.id.videoBuyMoney:
                //买
                goActivity();
                buyRlView.setVisibility(View.GONE);

                break;

            case R.id.videoKaiTongVip:
                //开通
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.videoCancelTv:
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.buttonBuyLl:

                if (movieDisBean != null && movieDisBean.getMovieBean() != null) {
                    DisBean bean = movieDisBean.getMovieBean();
                    if ("0".equals(bean.getIs_free())) {
                        if ("0".equals(bean.getHas_buy())) {
                            buyRlView.setVisibility(View.VISIBLE);
                        } else {
                            ToastUtil.showShortToast("您已经购买了该片");
                        }
                    } else {
                        ToastUtil.showShortToast("本视频免费");
                    }

                }

                break;
            case R.id.buttonCollectLl:
                //收藏
                if (isLogin()) {
                    collFun();
                }

                break;

            case R.id.videoDisSendTv:
                //点击发送
                sendCommentFun();
                break;
            case R.id.buttonDownLl:

                ToastUtil.showShortToast("开发中，敬请期待!");


                break;

            case R.id.play_btn:

                playVideo();

                break;


            case R.id.layout_30_tip:

                mSuperVideoPlayer.videoBuyRl.setVisibility(View.VISIBLE);

                break;

            case R.id.play_lock_rl:
                //点击了锁屏

                int tag = (int) mSuperVideoPlayer.lock_image.getTag();
                if (tag == 1) {
                    mSuperVideoPlayer.lock_image.setImageResource(R.mipmap.player_icon_lock);
                    mSuperVideoPlayer.lock_image.setTag(2);//锁屏

                    mSuperVideoPlayer.hideView(View.GONE);

                    mSuperVideoPlayer.resetHideTimer();

                } else {
                    mSuperVideoPlayer.lock_image.setImageResource(R.mipmap.player_icon_unlock);
                    mSuperVideoPlayer.lock_image.setTag(1);//锁屏

                    mSuperVideoPlayer.hideView(View.VISIBLE);

                    mSuperVideoPlayer.resetHideTimer();
                }


                break;

            case R.id.videoCancelLook:
                mSuperVideoPlayer.videoBuyRl.setVisibility(View.GONE);
                break;
            case R.id.videoConLook:


                boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
                if (flag) {
                    //登录了直接跳转

                    if (movieDisBean != null && movieDisBean.getMovieBean() != null) {
                        DisBean bean = movieDisBean.getMovieBean();
                        String money = bean.getScores();
                        String id = bean.getId();

                        checkMoney(money, id);

                    }


                } else {
                    //没有登录 先登录
                    startActivity(new Intent(this, LoginActivity.class));
                }


//
                break;


        }
    }


    /**
     * 显示简介
     */
    private void showJJie() {
        disFirstLl.setVisibility(View.GONE);
        disSecond.setVisibility(View.VISIBLE);
        bottomLine.setVisibility(View.GONE);
        videoDisBottomLl.setVisibility(View.GONE);

    }

    /**
     * 关闭简介
     */
    private void closeJJie() {

        disFirstLl.setVisibility(View.VISIBLE);
        disSecond.setVisibility(View.GONE);
        bottomLine.setVisibility(View.VISIBLE);
        videoDisBottomLl.setVisibility(View.VISIBLE);

    }


    /**
     * 视频的id
     *
     * @param id 视频的id
     */
    private void getVideoDis(String id) {

        String token = PreferenceUtils.getString(Constents.TOKEN, "");
//
        VideoDataRequest.getMovieDetail(token, id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    Log.i("Test", "response = " + response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");
                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {

                                JSONObject dataJson = jsonObject.getJSONObject("data");


                                MovieDisBean bean = new MovieDisBean();

                                List<MovieInfo69Bean> gussList = new ArrayList<>();

                                List<CommentInfoBean> comments = new ArrayList<>();


                                if (!dataJson.isNull("0")) {
                                    Gson gson = new Gson();
                                    String beanJson = dataJson.getString("0");
                                    DisBean bean69 = gson.fromJson(beanJson, DisBean.class);

//                                    if (bean69 != null) {
//                                        Log.i("Test", "bean69 = " + bean69.getHas_collect());
//                                    }

                                    bean.setMovieBean(bean69);

                                }


                                //猜你喜欢的数据
                                if (!dataJson.isNull("guess_like")) {
                                    JSONArray gussLike = dataJson.getJSONArray("guess_like");
                                    Gson gson = new Gson();
                                    for (int i = 0; i < gussLike.length(); i++) {
                                        JSONObject json = gussLike.getJSONObject(i);
                                        MovieInfo69Bean bean69 = gson.fromJson(json.toString(), MovieInfo69Bean.class);
                                        gussList.add(bean69);

                                    }

                                    bean.setGuess_like(gussList);
                                }

                                //评论列表
                                if (!dataJson.isNull("comments")) {
                                    Gson gson = new Gson();
                                    JSONArray commentStr = dataJson.getJSONArray("comments");

                                    long timeL = System.currentTimeMillis();

                                    for (int i = 0; i < commentStr.length(); i++) {
                                        JSONObject json = commentStr.getJSONObject(i);
                                        CommentInfoBean commentInfoBean = gson.fromJson(json.toString(), CommentInfoBean.class);
                                        String time = TimeUtils.createTime(timeL, commentInfoBean.getTime());
                                        commentInfoBean.setTime(time);

                                        if (commentInfoBean != null) {
                                            comments.add(commentInfoBean);
                                        }
                                    }

                                    bean.setComments(comments);
                                }
                                showUi(bean);
                                movieDisBean = bean;
                            }
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });


    }

    /**
     * 显示数据
     *
     * @param disBean 数据
     */
    @SuppressLint("SetTextI18n")
    private void showUi(MovieDisBean disBean) {

        DisBean bean = disBean.getMovieBean();

        if (bean != null) {
            //显示图片
            playUrl = bean.getFile_id();

            Log.i("Test", "playUrl = " + playUrl);

//            playUrl = url;

            String title = bean.getTitle();

            mSuperVideoPlayer.updateUI(title);
            mSuperVideoPlayer.setAllTime(bean.getTotal_time());


            Glide.with(this)
                    .load(bean.getImg_url())
                    .into(showFirstImg);


            //显示名字
            disName.setText(bean.getTitle());

            //显示类型和播放数
            int num = 0;
            try {
                if (!TextUtils.isEmpty(bean.getPlay_nums())) {
                    num = Integer.parseInt(bean.getPlay_nums());
                }

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            String sType;
            if (num > 10000) {
                String fNum = df.format(num * 1.0f / 10000);
                sType = "播放数：" + fNum + "万 " + bean.getType();
            } else {
                sType = "播放数：" + num + " " + bean.getType();
            }
            disDisTv.setText(sType);

            //显示积分
            if ("1".equals(bean.getIs_free())) {
                disJiFei.setVisibility(View.INVISIBLE);
            } else {
                disJiFei.setVisibility(View.VISIBLE);
            }

            disJiFei.setText(bean.getScores() + "代币");

            //显示名字
            disName1.setText(bean.getTitle());

            //显示简介
            disShowJianJie.setText(bean.getDesc());

            //显示名字
            videoNameShow.setText(bean.getTitle());

            //显示是收藏
            if ("0".equals(bean.getHas_collect())) {
                //没有藏收藏
                collImage.setImageResource(R.mipmap.video_dis_bottom_2);

            } else {
                //收藏了
                collImage.setImageResource(R.mipmap.video_dis_comment_c1);

            }

            videoBuyMoney.setText(bean.getScores() + "代币购买本片");


            coinNum = bean.getScores();

            if (mSuperVideoPlayer.moneyDelete != null) {
                mSuperVideoPlayer.moneyDelete.setText("扣除" + coinNum + "代币可以直接观看");
            }

            if ("0".equals(bean.getIs_free())) {

                if ("0".equals(bean.getHas_buy())) {
                    //检查播放时间
                    if (handler != null) {
                        handler.sendEmptyMessage(1);
                    }


                    if (mSuperVideoPlayer.layout_30_tip != null) {
                        mSuperVideoPlayer.layout_30_tip.setVisibility(View.VISIBLE);
                    }

                    isBuy = false;


                } else {
                    if (handler != null) {
                        handler.removeCallbacksAndMessages(null);
                    }

                    if (mSuperVideoPlayer.layout_30_tip != null) {
                        mSuperVideoPlayer.layout_30_tip.setVisibility(View.GONE);
                    }

                    isBuy = true;


                }
            } else {
                if (handler != null) {
                    handler.removeCallbacksAndMessages(null);
                }

                if (mSuperVideoPlayer.layout_30_tip != null) {
                    mSuperVideoPlayer.layout_30_tip.setVisibility(View.GONE);
                }

                isBuy = true;

            }

            //显示评论列表
            if (adapter != null) {

                //显示头部
                adapter.setMovieList(disBean.getGuess_like());


                CommentInfoBean bean1 = new CommentInfoBean();
                bean1.setType(0);

                if (disBean.getComments() == null) {
                    List<CommentInfoBean> list = new ArrayList<>();
                    list.add(bean1);
                    disBean.setComments(list);
                } else if (disBean.getComments().size() == 0) {
                    disBean.getComments().add(bean1);
                } else {
                    disBean.getComments().add(0, bean1);
                }

                adapter.setList(disBean.getComments());
                adapter.notifyDataSetChanged();
            }

        }


    }

    /**
     * 发送评论的功能
     */
    private void sendCommentFun() {

        boolean logFlag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (!logFlag) {

            startActivity(new Intent(this, LoginActivity.class));

            return;

        }


        if (!sendFlag) {
            return;
        }

        sendFlag = false;

        String msg = sendEt.getText().toString().trim();
        if (msg.length() > 0) {

            String token = PreferenceUtils.getString(Constents.TOKEN, "");

            VideoDataRequest.sendComment(token, videoId, msg, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    sendFlag = true;
                    if (isFinishing()) {
                        return;
                    }
                    ToastUtil.showShortToast("评论失败");

                }

                @Override
                public void onResponse(String response, int id) {
                    sendFlag = true;
                    if (isFinishing()) {

                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (!jsonObject.isNull("errno")) {
                            String code = jsonObject.getString("errno");
                            if ("0".equals(code)) {

                                if (sendEt != null) {
                                    sendEt.setText("");
                                }
                                sendFlag = true;
                                ToastUtil.showShortToast("评论成功");
                                //刷新数据
                                getVideoDis(videoId);

                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    /**
     * 收藏或者取消收藏的功能
     */
    private void collFun() {

        if (!colFlag) {
            return;
        }

        colFlag = false;

        String cloType = "";

        if (movieDisBean != null && movieDisBean.getMovieBean() != null) {

            String ty = movieDisBean.getMovieBean().getHas_collect();
            if ("0".equals(ty)) {
                //没有收藏
                cloType = "1";
            } else {
                cloType = "2";
            }

        }


        final String type = cloType;
        String token = PreferenceUtils.getString(Constents.TOKEN, "");
        VideoDataRequest.movieCollect(token, type, videoId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                colFlag = true;
                if (isFinishing()) {

                    return;
                }

                if ("1".equals(type)) {
                    ToastUtil.showShortToast("收藏失败");

                } else {
                    ToastUtil.showShortToast("取消收藏失败");
                }


            }

            @Override
            public void onResponse(String response, int id) {
                if (isFinishing()) {

                    return;
                }

                colFlag = true;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");
                        if ("0".equals(code)) {


                            if ("1".equals(type)) {
                                ToastUtil.showShortToast("收藏成功");

                                if (collImage != null) {
                                    collImage.setImageResource(R.mipmap.video_dis_comment_c1);
                                }

                                if (movieDisBean != null && movieDisBean.getMovieBean() != null) {

                                    movieDisBean.getMovieBean().setHas_collect("1");

                                }


                            } else {
                                ToastUtil.showShortToast("取消收藏成功");
                                if (collImage != null) {
                                    collImage.setImageResource(R.mipmap.video_dis_bottom_2);
                                }

                                if (movieDisBean != null && movieDisBean.getMovieBean() != null) {

                                    movieDisBean.getMovieBean().setHas_collect("0");

                                }

                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });


    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {


        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    if (handler != null) {
                        handler.removeMessages(1);
                    }


                    if (mSuperVideoPlayer != null && mSuperVideoPlayer.getmTxplayer() != null) {
                        try {

                            float time = mSuperVideoPlayer.getmTxplayer().getCurrentPlaybackTime();

                            if (time > TIME_LINE) {

                                if (handler != null) {
                                    handler.removeMessages(1);
                                    handler.sendEmptyMessageDelayed(2, 100);
                                }

                            } else {
                                if (handler != null) {
                                    handler.sendEmptyMessageDelayed(1, 1000);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (handler != null) {
                            handler.sendEmptyMessageDelayed(1, 1000);
                        }
                    }

                    break;

                case 2:
                    if (handler != null) {
                        handler.removeMessages(2);
                    }

                    if (mSuperVideoPlayer != null) {
                        mSuperVideoPlayer.pausePlay(true);

                        if (mSuperVideoPlayer.timeOverTv != null) {
                            mSuperVideoPlayer.timeOverTv.setVisibility(View.VISIBLE);
                        }

                        if (mSuperVideoPlayer.back_pl_1 != null) {
                            mSuperVideoPlayer.back_pl_1.setVisibility(View.VISIBLE);
                        }

                        if (mSuperVideoPlayer.title_1 != null) {
                            mSuperVideoPlayer.title_1.setVisibility(View.VISIBLE);
                        }

                        if (mSuperVideoPlayer.moneyDelete != null) {
                            mSuperVideoPlayer.moneyDelete.setText("扣除" + coinNum + "代币可以直接观看");
                        }

                        //时间要设置一下
                        mSuperVideoPlayer.updatePlayTime(TIME_LINE);

                        //进度条要设置一下
                        mSuperVideoPlayer.updatePlayProgress(TIME_LINE);

                        //设置界面
                        mSuperVideoPlayer.getmTxplayer().seek(TIME_LINE);

                        mSuperVideoPlayer.videoBuyRl.setVisibility(View.VISIBLE);

                    }


                    break;

            }

        }
    };

    private void myRegister() {

        if (receiver != null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("go_to_buy");
            filter.addAction("delete_con_success");
            registerReceiver(receiver, filter);
        }


    }

    private void myUnRegister() {

        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }


    }


    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if ("go_to_buy".equals(action)) {
                goActivity();
            } else if ("delete_con_success".equals(action)) {

//                videoplayer.layout30Show();
                if (handler != null) {
                    handler.removeMessages(1);
                }
                if (handler != null) {
                    handler.removeMessages(2);
                }

//                PreferenceUtils.setBoolean(VideoDisActivity.this, "timeOverFlag", false);

                DisBean bean = movieDisBean.getMovieBean();
                if (bean != null) {
                    bean.setHas_buy("1");
                }

                isBuy = true;


                if (mSuperVideoPlayer != null) {

                    if (mSuperVideoPlayer.timeOverTv != null) {
                        mSuperVideoPlayer.timeOverTv.setVisibility(View.GONE);
                    }

                    if (mSuperVideoPlayer.layout_30_tip != null) {
                        mSuperVideoPlayer.layout_30_tip.setVisibility(View.GONE);
                    }

                    if (mSuperVideoPlayer.back_pl_1 != null) {
                        mSuperVideoPlayer.back_pl_1.setVisibility(View.GONE);
                    }

                    if (mSuperVideoPlayer.title_1 != null) {
                        mSuperVideoPlayer.title_1.setVisibility(View.GONE);
                    }

                    mSuperVideoPlayer.loadVideo();

                    mSuperVideoPlayer.onResume();


                    mSuperVideoPlayer.resetHideTimer();


                }


            }
        }
    }


    private void goActivity() {

        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (flag) {
            //登录了直接跳转

            if (movieDisBean != null && movieDisBean.getMovieBean() != null) {
                DisBean bean = movieDisBean.getMovieBean();
                String money = bean.getScores();
                String id = bean.getId();

                Intent intent = new Intent(VideoDisActivity.this, MoneyBagActivity.class);
                intent.putExtra("buyMoney", money);
                intent.putExtra("movieId", id);
                startActivity(intent);
//                finish();
            }


        } else {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    public boolean isLogin() {
        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);

        if (!flag) {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }


        return flag;

    }


    /**
     * 播放监听
     */
    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        @Override
        public void onCloseVideo() {
            mSuperVideoPlayer.onDestroy();
            mPlayBtnView.setVisibility(View.VISIBLE);
            mSuperVideoPlayer.setVisibility(View.GONE);
            resetPageToPortrait();
        }

        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mSuperVideoPlayer.setPageType(MediaController.PageType.EXPAND);
            }
        }

        @Override
        public void onPlayFinish() {
            mPlayBtnView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onBack() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
            } else {
                finish();
            }
        }

        @Override
        public void onLoadVideoInfo(VodRspData data) {
        }
    };


    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
        }
    }


    /**
     * 播放视频
     */
    private void playVideo() {

        showFirstImg.setVisibility(View.GONE);

        mPlayBtnView.setVisibility(View.GONE);
        mSuperVideoPlayer.setVisibility(View.VISIBLE);
        backImage.setVisibility(View.GONE);


        mSuperVideoPlayer.setAutoHideController(true);
        TXPlayerAuthParam param = new TXPlayerAuthParam();

        //这个key可以播放
        param.appId = "1256725926";//1256725926   1400120590
//        param.appId = "1400120590";//正式
        param.fileId = playUrl;//playUrl表示的是视频的id
//        param.fileId = "7447398156551696700";

        //demo中的数据appId和fileId
//        param.appId = "1252463788";//
//        param.fileId = "4564972819219071568";//

        mSuperVideoPlayer.addVodInfo(param);
        playVideoWithFileId(param);

//        if (!TextUtils.isEmpty(playUrl)) {
//            mSuperVideoPlayer.setPlayUrl(playUrl);
//            mSuperVideoPlayer.loadVideo();
//        }


    }


    /**
     * 开始播放
     *
     * @param param 参数
     */
    private void playVideoWithFileId(TXPlayerAuthParam param) {
        TXPlayerAuthBuilder authBuilder = new TXPlayerAuthBuilder();
        try {
            if (!TextUtils.isEmpty(param.appId)) {
                authBuilder.setAppId(Integer.parseInt(param.appId));
            }
            String fileId = param.fileId;
            authBuilder.setFileId(fileId);

            if (mSuperVideoPlayer != null) {
                mSuperVideoPlayer.playFileID(authBuilder);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSuperVideoPlayer.loadVideo();
                    }
                });
            }
        } catch (NumberFormatException e) {
//            Toast.makeText(this, "请输入正确的AppId和FileId", Toast.LENGTH_SHORT).show();
        }
    }


    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == mSuperVideoPlayer) return;

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
            float height = DensityUtil.getWidthInPx(this);
            float width = DensityUtil.getHeightInPx(this);
            mSuperVideoPlayer.getLayoutParams().height = (int) width;
            mSuperVideoPlayer.getLayoutParams().width = (int) height;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = DensityUtil.getWidthInPx(this);
            float height = DensityUtil.dip2px(this, 200.f);
            mSuperVideoPlayer.getLayoutParams().height = (int) height;
            mSuperVideoPlayer.getLayoutParams().width = (int) width;
        }
    }


    /**
     * 检查钱
     */
    private void checkMoney(final String buyMoney, final String movieId) {

        if (!kMflag) {
            return;
        }

        kMflag = false;

        String token = PreferenceUtils.getString(null, Constents.TOKEN);

        PlayDataRequest.queryMoney(token, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                kMflag = true;

                if (activity != null) {
                    ToastUtil.showShortToast("查询代币数据出错");
                }

            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("money")) {
                                String money = jsonObject.getString("money");


                                try {
                                    float allM = Float.parseFloat(money);
                                    float buyM = Float.parseFloat(buyMoney);

                                    if (mSuperVideoPlayer != null && mSuperVideoPlayer.videoBuyRl != null) {
                                        mSuperVideoPlayer.videoBuyRl.setVisibility(View.GONE);
                                    }

                                    if (allM >= buyM) {
                                        //钱够了 直接扣币
                                        deleteMFun(movieId);
                                    } else {
                                        //钱不够 先充值 再扣币
                                        goActivity();
                                    }


                                } catch (NumberFormatException e) {
                                    e.printStackTrace();

                                }


                            } else {

                                if (activity != null) {
                                    ToastUtil.showShortToast("查询代币数据出错");
                                }
                            }


                        } else {
                            if (activity != null) {
                                ToastUtil.showShortToast("查询代币数据出错");
                            }


                        }

                    } else {
                        if (activity != null) {
                            ToastUtil.showShortToast("查询代币数据出错");
                        }


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    if (activity != null) {
                        ToastUtil.showShortToast("查询代币数据出错");
                    }

                }

                kMflag = true;


            }
        });


    }

    /**
     * 扣代币
     */
    private void deleteMFun(String movieId) {


        String token = PreferenceUtils.getString(null, Constents.TOKEN);

        PlayDataRequest.deleteMoney(token, movieId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                ToastUtil.showShortToast("扣除代币失败");
                kMflag = true;
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {
                            ToastUtil.showShortToast("扣除代币成功");
                            sendBroadcast(new Intent("delete_con_success").putExtra("id", id));
                        } else {
                            ToastUtil.showShortToast("扣除代币失败");

                        }
                    } else {
                        ToastUtil.showShortToast("扣除代币失败");

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showShortToast("扣除代币失败");

                }

                kMflag = true;
            }

        });
    }


}
